package cn.onepiece.smili.controller;

import cn.onepiece.smili.render.util.FileUtil;
import cn.onepiece.smili.render.util.ZipUtils;
import cn.onepiece.smili.service.SmiliService;
import com.wht.pirates.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @Author: haoting.wang
 * @Date: Created in 下午6:23 2017/5/25
 */
@RestController
@RequestMapping("/smili")
public class SmiliController {

    private static Logger logger = LoggerFactory.getLogger(SmiliController.class);

    public static final String CLASSPATH = SmiliController.class.getClassLoader().getResource("").getPath();

    @Autowired
    private SmiliService smiliService;
    /**
     * 生成代码，并打包下载
     * 
     * @param tableNames 表明，多个用，风格
     * @param basePackage 包名
     * @param response HttpServletResponse
     * @return
     * @throws Exception
     */
    @RequestMapping("/generator")
    public Result<String> generator(String[] tableNames, String basePackage,
                                    HttpServletResponse response) throws Exception {

        if (tableNames == null) {
            return Result.valueOfError("请输入需要生成的表名");
        }

        String generatorDir = null;
        String destZipFile = null;
        try {
            generatorDir = CLASSPATH+"generator";
            destZipFile = CLASSPATH+"generator.zip";

            File generatorFile = new File(generatorDir);
            smiliService.generator(tableNames, basePackage, generatorFile);

            ZipUtils.zipFolder(generatorDir,destZipFile);

            File zipFile = new File(destZipFile);
            FileUtil.downloadFile(zipFile, response);
        } catch (Exception e) {
            logger.error("generator create error message={}",e.getMessage());
            return Result.valueOfError("模板生成失败");
        } finally {
            // 删除服务端文件
            FileUtil.deleteDir(destZipFile);
            FileUtil.deleteDir(generatorDir);
        }
        return Result.valueOfSuccess("模板生成成功");
    }

}
